#pragma once

// 设计模式: 模版方法
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include <cstdlib>

namespace SocketModule
{
    using namespace LogModule;
    const static int gbacklog = 16;
    // 基类Socket里面的方法大部分都是纯虚函数,其派生类必须重写基类成员函数方法
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual void Bind(uint16_t port) = 0;
        virtual void Listen(int backlog) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(std::string &message) = 0;
        virtual int Connect(const std::string &server_ip,uint16_t port) = 0;

    public:
        // 创建套接字，包括创建socket，bind，listen
        void BuildListenSocket(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            Bind(port);
            Listen(backlog);
        }
        void BuildTcpClientSocketMethod()
        {
            SocketOrDie();
        }
        // void BuildUdpSocketMethod()
        // {
        //     SocketOrDie();
        //     Bind();
        // }
    };

    const static int defaultfd = -1;

    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _sockfd(defaultfd)
        {
        }
        TcpSocket(int fd) : _sockfd(fd) {}
        
        ~TcpSocket() {}
        void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0); // 这个::明确是调用全局socket函数，消除歧义
            if (_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(SOCKET_ERR);
            }

            LOG(LogLevel::INFO) << "socket success";
        }
        void Bind(uint16_t port) override
        {
            InetAddr local(port);

            int n = ::bind(_sockfd, local.NetAddrPtr(), local.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }
        void Listen(int backlog) override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                perror("listen failed: ");
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }
        std::shared_ptr<Socket> Accept(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = ::accept(_sockfd, CONV(peer), &len); // 返回值专门用于独立的客户端与服务器之间进行通信,实现监听与通信分离
            if (fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept warning...";
                return nullptr;
            }
            client->SetAddr(peer);
            return std::make_shared<TcpSocket>(fd);
        }
        void Close()
        {
            if (_sockfd > 0)
                ::close(_sockfd);
        }
        // 读
        int Recv(std::string *out) override
        {
            char buffer[1024];
            // read(_sockfd,buffer,sizeof(buffer)-1);
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
                return n;
            }
            return n;
        }
        // 写
        int Send(std::string &message) override
        {
            return ::send(_sockfd, message.c_str(), message.size(), 0);
        }
        int Connect(const std::string &server_ip,uint16_t port) override
        {
            InetAddr server(server_ip,port);
            return ::connect(_sockfd,server.NetAddrPtr(),server.NetAddrLen());
        }

    private:
        int _sockfd;
    };

    // class UdpSocket : public Socket
    // {

    // };

    // 假设当前作用域有一个名为 socket 的变量
    // int socket = 42;

    // // 情况1：直接调用 socket（可能被解析为变量）
    // int fd = socket(AF_INET, SOCK_DGRAM, 0); // 编译错误：将函数调用视为变量

    // // 情况2：使用 ::socket 明确指定全局函数
    // int fd = ::socket(AF_INET, SOCK_DGRAM, 0); // 正确：调用全局命名空间的 socket 函数
}